const { app, dialog, BrowserWindow, ipcMain, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const axios = require('axios');
const unzipper = require('unzipper');

let mainWindow;
const agreement = 'hiwi-AppCC';

function setDefaultProtocol() {
    let isSet = false;
    app.removeAsDefaultProtocolClient(agreement);

    if (process.platform === 'win32') {
      const resolvedPath = process.argv[1] ? path.resolve(process.argv[1]) : '';
      isSet = app.setAsDefaultProtocolClient(agreement, process.execPath, [resolvedPath]);
    } else {
        isSet = app.setAsDefaultProtocolClient(agreement, process.execPath);
    }

    console.log('是否注册成功', isSet);
}

function watchProtocol() {
    const AGREEMENT_REGEXP = new RegExp(`^${agreement}://`);

    app.on('open-url', (event, url) => {
        event.preventDefault();
        const isProtocol = AGREEMENT_REGEXP.test(url);
        if (isProtocol) {
            console.log('获取协议链接:', url);
        }
    });

    app.on('second-instance', (event, commandLine) => {
        commandLine.forEach((str) => {
            if (AGREEMENT_REGEXP.test(str)) {
                console.log('获取协议链接:', str);
                dialog.showMessageBox({
                    type: 'info',
                    message: 'Windows 自定义协议打开',
                    detail: `自定义协议链接: ${str}`,
                });
            }
        });
    });
}
// 注册并监听自定义协议
setDefaultProtocol();
watchProtocol();
// 创建窗口并加载 HTML 页面
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  mainWindow.loadFile('views/index.html');

  // 当窗口加载完成后执行下载和解压逻辑
  mainWindow.webContents.on('did-finish-load', () => {
    main();
  });
}

// 向窗口发送日志
function sendLog(message) {
    // 只在窗口存在时发送日志
    if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents) {
      mainWindow.webContents.send('log', message);
    }
  // if (mainWindow && mainWindow.webContents) {
  //   mainWindow.webContents.send('log', message);
  // }
}

// 下载文件
// 下载文件
async function downloadFile(url, filePath) {
  sendLog('1、开始下载文件...');
  // 确保文件的父目录存在
  const fileDir = path.dirname(filePath);
  if (!fs.existsSync(fileDir)) {
    fs.mkdirSync(fileDir, { recursive: true }); // 递归创建路径
  }

  const response = await axios({
    url: url,
    method: 'GET',
    responseType: 'stream',
  });

  return new Promise((resolve, reject) => {
    const writer = fs.createWriteStream(filePath);
    response.data.pipe(writer);
    writer.on('finish', () => {
      sendLog('2、文件下载完成');
      resolve();
    });
    writer.on('error', reject);
  });
}

// 获取系统路径
function getSystemPath() {
  const platform = os.platform();
  if (platform === 'win32') {
    return path.join(os.homedir(), 'AppData', 'Local', 'HiwiApplication', 'app');
  } else if (platform === 'darwin') {
    return path.join(os.homedir(), 'Library', 'Application Support', 'HiwiApplication', 'app');
  }
}

// 解压并重命名
async function extractAndRename(zipPath, extractTo) {
  // sendLog(`3、正在解压文件到: `);
  sendLog(`${extractTo}`);
  await fs.createReadStream(zipPath)
    .pipe(unzipper.Extract({ path: extractTo }))
    .promise();

  // 获取解压文件夹中的所有内容
  const files = fs.readdirSync(extractTo);
  const extractedFolder = files.find(file => fs.lstatSync(path.join(extractTo, file)).isDirectory());
  if (extractedFolder) {
    // 删除压缩包文件
    fs.unlinkSync(zipPath);
    sendLog(`3、插件已更新！`);
  } else {
    sendLog('没有找到解压后的文件夹');
  }
}
// 主流程
async function main() {
  const url = 'https://open.cloudycentury.net:89/pyplugins/dcc_app/ext1';
  const systemPath = getSystemPath();
  const zipPath = path.join(systemPath, 'plugin.zip');

  try {
    // 检查 systemPath 是否存在
    const parentPath = systemPath.replace('/app', ''); // 获取父级路径
    if (!fs.existsSync(parentPath)) {
      // 如果父文件夹不存在，创建并打开
      fs.mkdirSync(parentPath, { recursive: true });
      sendLog(`文件夹 ${parentPath} 已创建，正在打开...`);
      shell.openPath(parentPath);
    } else {
      fs.mkdirSync(parentPath, { recursive: true });
      sendLog(`文件夹 ${parentPath} 已存在，跳过创建。`);
      shell.openPath(parentPath);
    }

    // 下载文件
    sendLog('正在下载文件...');
    await downloadFile(url, zipPath);

    // 解压并重命名
    sendLog('解压文件中...');
    await extractAndRename(zipPath, systemPath);

    // 提示并延时关闭应用
    sendLog('10秒后自动关闭应用...');
    setTimeout(() => {
      app.quit();
    }, 10000);
  } catch (error) {
    sendLog(`发生错误: ${error.message}`);
  }
}

// 当 Electron 准备好时创建窗口
app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});